//
//  WUImageBrowseView.m
//  kztool
//
//  Created by 毛韶谦 on 16/6/24.
//  Copyright © 2016年 wutan. All rights reserved.
//

#import "WUImageBrowseView.h"
#import "UIImage+Aspect.h"


@interface WUPreviewImageCell()<UIScrollViewDelegate>

@property(nonatomic,strong) UIScrollView *imageScrollView;

@end

@implementation WUPreviewImageCell

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        [self initialize];
    }
    return self;
}

-(void)initialize {
    _imageScrollView = [[UIScrollView alloc] init];
    _imageScrollView.delegate = self;
    _imageScrollView.bounces = YES;
    _imageScrollView.maximumZoomScale = 2;
    _imageScrollView.minimumZoomScale = 1;
    [self.contentView addSubview:_imageScrollView];
    
    _imageView = [[UIImageView alloc] init];
    _imageView.contentMode = UIViewContentModeScaleAspectFit;
    _imageView.userInteractionEnabled = true;
    [_imageScrollView addSubview:_imageView];
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
    singleTap.numberOfTapsRequired = 1;
    singleTap.numberOfTouchesRequired = 1;
    [_imageScrollView addGestureRecognizer:singleTap];
    
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
    doubleTap.numberOfTapsRequired = 2;
    doubleTap.numberOfTouchesRequired = 1;
    [_imageView addGestureRecognizer:doubleTap];
    [singleTap requireGestureRecognizerToFail:doubleTap];
}

-(void)layoutSubviews {
    [super layoutSubviews];
    [self layout];
}

-(void)layout {
    _imageScrollView.frame = CGRectMake(15, 0, CGRectGetWidth(self.frame) - 30, CGRectGetHeight(self.frame));
    if(_imageView.image) {
        CGRect rect = [_imageView.image rectAspectFitRectForSize:_imageScrollView.frame.size];
        _imageView.frame = rect;
    } else {
        _imageView.frame = _imageScrollView.bounds;
    }
}

-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.imageView;
}

-(void)scrollViewDidZoom:(UIScrollView *)scrollView {
    CGFloat offsetX = scrollView.bounds.size.width > scrollView.contentSize.width ? (scrollView.bounds.size.width - scrollView.contentSize.width) / 2 : 0.0;
    CGFloat offsetY = scrollView.bounds.size.height > scrollView.contentSize.height ? (scrollView.bounds.size.height - scrollView.contentSize.height) / 2 : 0.0;
    _imageView.center = CGPointMake(scrollView.contentSize.width / 2 + offsetX, scrollView.contentSize.height / 2 + offsetY);
}

-(void)setImageZoom:(CGFloat)scale {
    [_imageScrollView setZoomScale:scale animated:NO];
}

#pragma -mark 点击图片

-(void)singleTap:(UIGestureRecognizer*)sender {
    if(self.delegate && [self.delegate respondsToSelector:@selector(previewImageCellDidSelected:)]) {
        [self.delegate previewImageCellDidSelected:self];
    }
}

-(void)doubleTap:(UIGestureRecognizer*)sender {
    CGFloat scale = _imageScrollView.zoomScale;
    scale = scale < 2.0 ? 2.0 : 1;
    [_imageScrollView setZoomScale:scale animated:YES];
}


@end






#define WUIMAGE_DEFAULT_FRAME CGRectMake(-15, 0, CGRectGetWidth(self.frame) + 30, CGRectGetHeight(self.frame))

NSString *const WUImageBrowseViewCellIdentifier = @"WUImageBrowseViewCellIdentifier";

@interface WUImageBrowseView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,WUPreviewImageCellDelegate>

@property(nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic,strong) UIPageControl *pageControl;
@property(nonatomic,strong) UILabel *pageLabel;

@end

@implementation WUImageBrowseView

-(instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        [self initialize];
    }
    return self;
}

-(void)initialize {
    self.backgroundColor = [UIColor blackColor];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:WUIMAGE_DEFAULT_FRAME collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.pagingEnabled = YES;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.showsVerticalScrollIndicator = NO;
    [_collectionView registerClass:[WUPreviewImageCell class] forCellWithReuseIdentifier:WUImageBrowseViewCellIdentifier];
    [self addSubview:_collectionView];
}

-(void)setImages:(NSArray *)images {
    _images = images;
    [self updatePageControlDisplay:0 count:images.count];
    [_collectionView reloadData];
}

-(void)setPageControlStyle:(WUPageControlStyle)pageControlStyle {
    _pageControlStyle = pageControlStyle;
    
    switch (_pageControlStyle) {
        case WUPageControlStyleSystem: {
            if(!_pageControl) {
                _pageControl = [[UIPageControl alloc] init];
                _pageControl.pageIndicatorTintColor = [UIColor grayColor];
                _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
                _pageControl.hidesForSinglePage = YES;
            }
            [self addSubview:_pageControl];
            if(_pageLabel) [_pageLabel removeFromSuperview];
        }
            
            break;
        case WUPageControlStyleUILabel: {
            if(!_pageLabel) {
                _pageLabel = [[UILabel alloc] init];
                _pageLabel.textColor = [UIColor whiteColor];
                _pageLabel.font = [UIFont systemFontOfSize:14];
                _pageLabel.textAlignment = NSTextAlignmentCenter;
            }
            [self addSubview:_pageLabel];
            if(_pageControl) [_pageControl removeFromSuperview];
        }
            break;
        default:
            break;
    }
}

-(void)layoutSubviews {
    [super layoutSubviews];
    self.collectionView.frame = WUIMAGE_DEFAULT_FRAME;
    
    CGRect pageFrame = CGRectMake(0, CGRectGetHeight(self.frame) - 40, CGRectGetWidth(self.frame), 20);
    if(_pageControl) {
        _pageControl.frame = pageFrame;
    } else if(_pageLabel) {
        _pageLabel.frame = pageFrame;
    }
}

#pragma -mark collectionView delegate

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if(!_images) {
        return 0;
    }
    return _images.count;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return collectionView.frame.size;
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    WUPreviewImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:WUImageBrowseViewCellIdentifier forIndexPath:indexPath];
    [cell setImageZoom:1];
    cell.delegate = self;
    id imageItem = _images[indexPath.row];
    
    if([imageItem isKindOfClass:[UIImage class]]) {
        cell.imageView.image = imageItem;
        [cell layout];
    } else if([imageItem isKindOfClass:[NSString class]]) {
        
        __weak typeof(cell) weakCell = cell;
        
        [cell.imageView load:imageItem placeholderImage:[UIImage imageNamed:@"BKGDDefault"] progress:nil completed:^(UIImage *image, NSError *error, NSURL *imageURL) {
            if(!image) {
                return;
            }
            
            if(!weakCell) {
                return;
            }
            
            __strong typeof(weakCell) strongCell = weakCell;
            [strongCell.imageView setImage:image];
            [strongCell layout];
        }];
    }
    
    return cell;
}

-(void)updatePageControlDisplay:(NSInteger)currentPage count:(NSInteger)count {
    if(_pageControl) {
        _pageControl.currentPage = currentPage;
        _pageControl.numberOfPages = count;
    } else if(_pageLabel) {
        NSString *text = [NSString stringWithFormat:@"%ld / %ld", (long)(currentPage + 1), (long)count];
        _pageLabel.text = text;
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offsetX = scrollView.contentOffset.x;
    NSInteger page = offsetX / CGRectGetWidth(scrollView.frame);
    [self updatePageControlDisplay:page count:_images.count];
}

-(void)show:(UIView*)view startFrame:(CGRect)startFrame foregroundImage:(UIImage*)image {
    UIView *backView = [[UIView alloc] initWithFrame:self.bounds];
    backView.backgroundColor = [UIColor blackColor];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:startFrame];
    imageView.image = image;
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    [backView addSubview:imageView];
    
    [view addSubview:backView];
    
    CGRect tf = [image rectAspectFitRectForSize:view.frame.size];
    [UIView animateWithDuration:0.3 animations:^{
        imageView.frame = CGRectMake(CGRectGetWidth(self.frame) / 2 - CGRectGetWidth(tf) / 2, CGRectGetHeight(self.frame) / 2 - CGRectGetHeight(tf) / 2, CGRectGetWidth(tf), CGRectGetHeight(tf));
    } completion:^(BOOL finished) {
        [backView removeFromSuperview];
        [view addSubview:self];
        [self updatePageControlDisplay:self.currentPage count:self.images.count];
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentPage inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    }];
}

-(void)show:(UIView*)view {
    [view addSubview:self];
    [self updatePageControlDisplay:self.currentPage count:self.images.count];
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:self.currentPage inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}

-(void)previewImageCellDidSelected:(WUPreviewImageCell*)cell {
    if(self.delegate && [self.delegate respondsToSelector:@selector(imageBrowseView:willCloseAtIndex:)]) {
        
        NSArray<UIView*> *controls = [self subviews];
        for (UIView *view in controls) {
            [view removeFromSuperview];
        }
        
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.image = cell.imageView.image;
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;
        imageView.frame = cell.imageView.frame;
        [self addSubview:imageView];
        
        NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
        CGRect rect = [self.delegate imageBrowseView:self willCloseAtIndex:indexPath.row];
        if(CGRectEqualToRect(CGRectZero, rect)) {
            [self dissmiss];
        } else {
            
            self.backgroundColor = [UIColor clearColor];
            
            [UIView animateWithDuration:0.3 animations:^{
                imageView.frame = rect;
            } completion:^(BOOL finished) {
                [self removeFromSuperview];
            }];
        }
    } else {
        [self dissmiss];
    }
}

-(void)dissmiss {
    [UIView animateWithDuration:1 animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

@end
